package com.ehome.poct.core.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.ehome.poct.base.api.enums.BusinessOrderTypeEnums;
import com.ehome.poct.base.api.enums.StripTypeEnums;
import com.ehome.poct.core.api.constant.EhomeConst;
import com.ehome.poct.core.api.constant.enums.CheckMessageTypeEnums;
import com.ehome.poct.core.api.dto.message.OriginCheckOrderMsg;
import com.ehome.poct.core.api.dto.message.QueueMessageOriginDTO;
import com.ehome.poct.core.api.dto.order.TestOrderDTO;
import com.ehome.poct.core.api.dto.order.TestOrderItemDTO;
import com.ehome.poct.core.api.mapping.CheckEventMapping;
import com.ehome.poct.core.constant.OrderBizCodeEnums;
import com.ehome.poct.core.repository.order.TestOrderItemRepository;
import com.ehome.poct.core.service.rpc.ClinicClient;
import com.ehome.poct.core.utils.EHomeAssert;
import com.ehome.rocketmq.RocketMqTemplate;
import lombok.Data;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.assertj.core.util.Lists;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @auther: kuiba.peng
 * @date: 2022/11/11 17:48
 * @description:
 */
@Service
@RequiredArgsConstructor
@Slf4j
@Data
public class CheckEventServiceImpl {
    private final ClinicClient clinicClient;

    private final CheckEventMapping checkEventMapping;

    private final RocketMqTemplate rocketMqTemplate;

    private final TestOrderItemRepository orderItemRepository;

    @Value("${notify.detail.env}")
    private String enyType;


    /**
     * 发送检查事件
     *
     * @param orderDTO 源订单信息
     */
    public boolean sendCheckEvent(TestOrderDTO orderDTO) {
        EHomeAssert.notNull(orderDTO, OrderBizCodeEnums.TEST_ORDER_IS_NULL);
        var termClinicDO = clinicClient.getById(orderDTO.getClinicId());
        // 诊所为空
        if (Objects.isNull(termClinicDO)) {
            return Boolean.FALSE;
        }
        // 特殊账号
        if (EhomeConst.SPECIAL_ACCOUNT_TYPE.equals(termClinicDO.getSpecialAccountType())) {
            return Boolean.FALSE;
        }

        // 支付金额小于最小支付金额 或者 回调环境值不等于1
        if (StrUtil.equals(enyType, "1") || EhomeConst.MIN_PAY_MONEY.compareTo(orderDTO.getPayMoney()) <= 0) {
            String pubTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
            OriginCheckOrderMsg checkOrderMsg = new OriginCheckOrderMsg().setOrderId(String.valueOf(orderDTO.getTestOrderId()));
            QueueMessageOriginDTO<OriginCheckOrderMsg> messageOriginDTO = checkEventMapping.toOrderEvent(pubTime, checkOrderMsg);
            CheckMessageTypeEnums checkMessageType = CheckMessageTypeEnums.JYB;
            if (BusinessOrderTypeEnums.PRE_TRADE.equals(orderDTO.getBusinessOrderType())) {
                checkMessageType = preOrder2DeviceType(orderDTO);
            }
            messageOriginDTO.getData().setDeviceType(checkMessageType.getType());
            messageOriginDTO.setMd5Sign();
            String message = JSONUtil.parseObj(messageOriginDTO).toString();
            try {
                log.info("发送消息 {} {}", EhomeConst.ORIGIN_ORDER_POCT_TOPIC, message);
                rocketMqTemplate.send(EhomeConst.ORIGIN_ORDER_POCT_TOPIC, orderDTO.getTestOrderNo(), message);
            } catch (Exception ex) {
                log.error("发送消息失败！{}", ex.getMessage());
                return Boolean.FALSE;
            }
            return Boolean.TRUE;
        }
        return Boolean.FALSE;
    }

    /**
     * 支付前置订单特殊处理
     *
     * @param orderDTO
     * @return
     */
    public CheckMessageTypeEnums preOrder2DeviceType(TestOrderDTO orderDTO) {
        List<TestOrderItemDTO> orderItemDTOList = orderItemRepository.list(new TestOrderItemDTO().setTestOrderNo(orderDTO.getTestOrderNo()));
        List<Integer> stripCodeList = orderItemDTOList.stream().map(TestOrderItemDTO::getStripTypeCode).collect(Collectors.toList());
        boolean flag = CollUtil.containsAny(stripCodeList, Lists.newArrayList(StripTypeEnums.U_CRP_SAA_BLD_REPORT.getStripTypeCode(), StripTypeEnums.BLD.getStripTypeCode()));
        return flag ? CheckMessageTypeEnums.XCG : CheckMessageTypeEnums.JYB;
    }
}
